//
//  HEHealthHisViewController.m
//  HealthFamily
//
//  Created by LOOK on 2020/12/27.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthHisViewController.h"
#import "HEPickerView.h"
#import "HEHealthHisCell.h"
#import "HEHealthHisItems.h"

@interface HEHealthHisViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray <HEHealthHisItems *> * dataSourceArr;

@end

@implementation HEHealthHisViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPicker)];
//    [self.view addGestureRecognizer:tap];
    
    self.title = @"健康史";
    [self setNav];
    
    [self setData];
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    [self.view addSubview:self.tableView];
}

- (void)setNav {
    [self zx_setRightBtnWithText:@"保存" clickedBlock:^(UIButton * _Nonnull btn) {
        [self updateUserInfo];
    }];
    self.zx_navRightBtn.zx_tintColor = CNavBgColor;
}

- (void)setData {
    _dataSourceArr = @[].mutableCopy;
    
    NSArray *titleArr = @[@"疾病史", @"家族病史", @"药物过敏", @"食物/接触过敏史", @"个人习惯"];
    NSArray *placehods = @[@"疾病名称", @"疾病名称", @"药物名称", @"其它食物或过敏源", @"其它个人习惯"];

    NSArray *diseArr = @[@"无", @"高血压", @"糖尿病", @"冠心病", @"慢性阻塞性肺疾病", @"恶性肿瘤", @"脑卒中", @"重性精神疾病", @"结核病", @"肝炎", @"其他法定传染病"];
    NSArray *familyArr = @[@"无", @"高血压", @"糖尿病", @"冠心病", @"慢性阻塞性肺疾病", @"恶性肿瘤", @"脑卒中", @"重性精神疾病", @"结核病", @"肝炎", @"先天畸形",@"其他"];

    NSArray *guomArr = @[@"无", @"青霉素", @"磺胺", @"链霉素"];
    NSArray *foodArr = @[@"无", @"牛奶", @"鸡蛋", @"花生", @"小麦", @"海鲜", @"花粉", @"动物皮屑", @"香料"];
    NSArray *personArr = @[@"低头族", @"久坐", @"久站", @"久趟", @"强忍大小便", @"跷二郎腿", @"喝酒", @"熬夜", @"吸烟", @"饭后卧床", @"不常锻炼", @"如厕玩手机", @"不喜喝水"];

    NSArray *data = @[diseArr, familyArr, guomArr, foodArr, personArr];
//    NSArray *data = @[diseArr];
 
    NSInteger i = 0;
    for (NSArray *arr in data) {
        HEHealthHisItems *model = [HEHealthHisItems new];
        model.items = @[].mutableCopy;
        model.title = titleArr[i];
        model.placeHolde = [NSString stringWithFormat:@"请输入%@以逗号分隔", placehods[i]];
        
        for (NSString *str in arr) {
            HEHealthHisItemModel *item = [HEHealthHisItemModel new];
            item.isSelect = NO;
            item.title = str;

            [model.items addObject:item];
        }
        
        [_dataSourceArr addObject:model];
        i++;
    }
    
    NSMutableArray *otherDise = @[].mutableCopy;
    NSMutableArray *otherFamily = @[].mutableCopy;
    NSMutableArray *otherDrugs = @[].mutableCopy;
    NSMutableArray *otherFood = @[].mutableCopy;
    NSMutableArray *otherAllerg = @[].mutableCopy;

    // 设置默认值
    // 疾病史
    for (HEUserDisease *dise in _model.user_disease) {
        
        BOOL isContiant = NO;
        for (HEHealthHisItemModel *item in _dataSourceArr[0].items) {
            if ([item.title isEqualToString:dise.disease_name]) {
                item.isSelect = YES;
                isContiant = YES;
            }
        }
        if (!isContiant) {
            [otherDise addObject:dise.disease_name];
        }
    }
    _dataSourceArr[0].content = [otherDise componentsJoinedByString:@","];
    
    // 家族疾病史
    for (HEUserFamily *dise in _model.user_family) {
        BOOL isContiant = NO;
        for (HEHealthHisItemModel *item in _dataSourceArr[1].items) {
            if ([item.title isEqualToString:dise.disease]) {
                item.isSelect = YES;
                isContiant = YES;
            }
        }
        if (!isContiant) {
            [otherFamily addObject:dise.disease];
        }
    }
    _dataSourceArr[1].content = [otherFamily componentsJoinedByString:@","];

    // 药物过敏
    for (HEDrugsModel *dise in _model.user_drugs) {
        BOOL isContiant = NO;
        for (HEHealthHisItemModel *item in _dataSourceArr[2].items) {
            if ([item.title isEqualToString:dise.drugs_name]) {
                item.isSelect = YES;
                isContiant = YES;
            }
        }
        if (!isContiant) {
            [otherDrugs addObject:dise.drugs_name];
        }
    }
    _dataSourceArr[2].content = [otherDrugs componentsJoinedByString:@","];

    // 食物过敏
    for (HEUserAllergic *dise in _model.user_allergic) {
        BOOL isContiant = NO;
        for (HEHealthHisItemModel *item in _dataSourceArr[3].items) {
            if ([item.title isEqualToString:dise.allergic_name]) {
                item.isSelect = YES;
                isContiant = YES;
            }
        }
        if (!isContiant) {
            [otherFood addObject:dise.allergic_name];
        }
    }
    _dataSourceArr[3].content = [otherFood componentsJoinedByString:@","];
    
    // 个人习惯
    for (HEUserHabits *dise in _model.user_habits) {
        BOOL isContiant = NO;
        for (HEHealthHisItemModel *item in _dataSourceArr[4].items) {
            if ([item.title isEqualToString:dise.habits]) {
                item.isSelect = YES;
                isContiant = YES;
            }
        }
        if (!isContiant) {
            [otherAllerg addObject:dise.habits];
        }
    }
    _dataSourceArr[4].content = [otherAllerg componentsJoinedByString:@","];
}

- (void)showPicker {
    HEPickerView *picker = [[HEPickerView alloc] init];
    picker.title = @"吸烟室";
    picker.subTitles = @[@"是否吸烟", @"烟龄", @"每天数量"];
    picker.dataSource = @[
        @[@"否", @"是", @"已戒烟"],
        @[@"0年", @"1~2年", @"2~4年", @"6~8年", @"8~10年", @"10年以上"],
        @[@"不吸烟", @"1~2根", @"2~4根", @"4~6根", @"6~8根", @"8~10根", @"10根以上"]
    ];
    picker.selectValues = @[@"是", @"1~2年", @"4~6根"];
    [picker show];
    picker.resultModelArrayBlock = ^(NSArray<HEPickerResModel *> * _Nullable resultModelArr) {
        
    };
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
 
        [_tableView registerClass:[HEHealthHisCell class] forCellReuseIdentifier: @"HEHealthHisCell"];
    }
    return _tableView;
}

- (void)updateUserInfo {
     
    NSMutableDictionary *dict = @{}.mutableCopy;
    
    NSMutableDictionary *user_info = @{}.mutableCopy;
    [user_info setValue: _model.user_info.pid forKey:@"pid"];
    [dict setValue: user_info forKey:@"user_info"];


    // 替换所有逗号拼接中文逗号
    for (HEHealthHisItems *model in _dataSourceArr) {
        NSString *strUrl = [model.content stringByReplacingOccurrencesOfString:@"，" withString:@","];
        model.content = strUrl;
    }
    
    [dict setValue: [self dealDataKey:@"disease_name" index:0] forKey:@"user_disease"];
    [dict setValue: [self dealDataKey:@"disease" index:1] forKey:@"user_family"];
    [dict setValue: [self dealDataKey:@"drugs_name" index:2] forKey:@"user_drugs"];
    [dict setValue: [self dealDataKey:@"allergic_name" index:3] forKey:@"user_allergic"];
    [dict setValue: [self dealDataKey:@"habits" index:4] forKey:@"user_habits"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KsaveAllInfo parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues: responseObject];
        if (response.success) {
            [Dialog toastBottom: @"修改成功"];
            
            if (self.backBlock) {
                self.backBlock();
            }
            // todo: 实名认证信息更新
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (NSArray *)dealDataKey:(NSString *)key index:(NSInteger)index{
    NSMutableArray *section = @[].mutableCopy;
    
    NSMutableArray *allItemStrArr = @[].mutableCopy;
    HEHealthHisItems *model = _dataSourceArr[index];
    
    // 提取出所有选择tag的
    for (HEHealthHisItemModel *item in model.items) {
        if (item.isSelect) {
            [allItemStrArr addObject:item.title];
        }
    }
    
    // 处理输入
    NSArray *others = [model.content componentsSeparatedByString:@","];
    for (NSString *str in others) {
        if (![DYTools isBlankString:str]) {
            [allItemStrArr addObject:str];
        }
    }
    
    for (NSString *str in allItemStrArr) {
        NSMutableDictionary *subDict = @{}.mutableCopy;
        [subDict setValue: str forKey:key];
        [section addObject:subDict];
    }
    return section;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEHealthHisCell *cell = [_tableView dequeueReusableCellWithIdentifier: @"HEHealthHisCell"];
    [cell configCellWithModel:self.dataSourceArr[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HEHealthHisItems *model = self.dataSourceArr[indexPath.row];
 
    return [tableView fd_heightForCellWithIdentifier: @"HEHealthHisCell" cacheByIndexPath:indexPath configuration:^(HEHealthHisCell *cell) {
        [cell configCellWithModel:self.dataSourceArr[indexPath.row]];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEHealthHisItems *model = self.dataSourceArr[indexPath.row];
 
}

@end
